<!-- 编辑弹窗 -->
<template>
  <div class="ele-body">
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="isUpdate ? '修改落地页' : '添加落地页'"
      :visible="visible"
      custom-class="ele-dialog-form"
      @update:visible="updateVisible"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :sm="12">
            <el-form-item label="站点名称:" prop="SiteName">
              <el-input
                v-model="form.SiteName"
                clearable
                placeholder="请输入站点名称"
              />
            </el-form-item>

            <el-form-item label="落地页:" prop="DomainUrl">
              <el-input
                v-model="form.DomainUrl"
                clearable
                placeholder="请输入落地页"
              />
            </el-form-item>

            <el-form-item label="推广市场:" prop="bazaar">
              <el-select
                v-model="form.bazaar"
                class="ele-block"
                clearable
                placeholder="请选择推广市场"
                @change="bazaarChange"
              >
                <el-option
                  v-for="item in bazaarList"
                  :key="item.id"
                  :disabled="item.status === 0"
                  :label="
                    `[` +
                    [
                      '',
                      '百度SEM竞价',
                      '百度信息流',
                      '巨量引擎',
                      '搜狗推广',
                      '卧龙推广',
                      '360点睛',
                    ][item.platform] +
                    `] ` +
                    item.name
                  "
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="展示模式:">
              <el-select
                v-model="form.SiteModel"
                class="ele-block"
                clearable
                placeholder="请选择展示模式"
              >
                <el-option
                  v-for="item in modelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="站点源码:">
              <el-row>
                <el-col :span="18">
                  <el-input
                    v-model="form.SiteSource"
                    clearable
                    placeholder="请上传站点源码"
                  />
                </el-col>
                <el-col :span="6">
                  <el-upload
                    :action="baseURLUpload()"
                    :before-upload="beforeUpload"
                    :disabled="uploadLoading"
                    :headers="headersUpload"
                    :on-error="errorUpload"
                    :on-progress="progressUpload"
                    :on-success="successUpload"
                    :show-file-list="false"
                    style="
                      position: relative;
                      display: inline-block;
                      margin-left: 10px;
                    "
                  >
                    <el-button
                      :disabled="uploadLoading"
                      :loading="uploadLoading"
                      icon="el-icon-upload"
                      size="small"
                      style="height: 34px"
                      type="primary"
                      >{{ uploadText }}
                    </el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="AB页面:">
              <el-switch
                v-model="form.abswitch"
                :active-value="1"
                :inactive-value="0"
                @change="abpage"
              />
              <el-popover
                content="选择开启后根据不同场景展示不同页面。"
                placement="top-start"
                trigger="hover"
                width="240"
              >
                <i
                  slot="reference"
                  class="el-icon-_question"
                  style="vertical-align: middle; margin-left: 8px"
                ></i>
              </el-popover>
            </el-form-item>

            <el-form-item label="A页面目录:">
              <el-input
                v-model="form.aPage"
                clearable
                placeholder="/www/wwwroot/baidu.com/zhen"
              />
            </el-form-item>

            <el-form-item v-if="showbPage" label="B页面目录:">
              <el-input
                v-model="form.bPage"
                clearable
                placeholder="/www/wwwroot/lz.sxltlvx.cn/jia"
              />
            </el-form-item>
          </el-col>

          <el-col :sm="12">
            <el-form-item prop="url">
              <span slot="label"
                >访问URL
                <el-popover
                  placement="top-start"
                  title="访问URL说明"
                  trigger="hover"
                >
                  <p>
                    比如你的网站是 http://www.baidu.com/index.html 请填写
                    http://www.baidu.com/
                  </p>
                  <p>
                    比如你的网站是 http://www.baidu.com/dx/index.html 请填写
                    http://www.baidu.com/dx/
                  </p>
                  <template slot="reference">
                    <i
                      class="el-tooltip el-icon-_question"
                      style="cursor: pointer; margin-right: 10px"
                    ></i>
                  </template>
                </el-popover>
                <span style="margin-left: -5px">:</span>
              </span>
              <el-input
                v-model="form.url"
                clearable
                placeholder="请输入访问地址, 比如http://www.baidu.com/"
              />
            </el-form-item>

            <el-form-item>
              <span slot="label"
                >绑定域名
                <el-popover
                  content="绑定域名应用于AB页切换, 请查看教程填写。"
                  placement="top-start"
                  title="绑定域名说明"
                  trigger="hover"
                  width="320"
                >
                  <template slot="reference">
                    <i
                      class="el-tooltip el-icon-_question"
                      style="cursor: pointer; margin-right: 10px"
                    ></i>
                  </template>
                </el-popover>
                <span style="margin-left: -5px">:</span>
              </span>
              <el-row>
                <el-col :span="16">
                  <el-input
                    v-model="form.Domains"
                    :maxlength="100"
                    clearable
                    placeholder="请输入落地页绑定域名"
                  />
                </el-col>
                <el-col :span="8">
                  <el-button
                    style="margin-left: 10px"
                    plain
                    @click="helpImage(false)"
                    >查看域名</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="宝塔Hook:">
              <el-row>
                <el-col :span="16">
                  <el-input
                    v-model="form.btAddress"
                    :maxlength="100"
                    clearable
                    placeholder="请输入宝塔WebHook地址"
                  />
                </el-col>
                <el-col :span="8">
                  <el-button
                    style="margin-left: 10px"
                    plain
                    @click="helpVideo(false)"
                    >安装代码</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="Hook密匙:">
              <el-input
                v-model="form.btKey"
                clearable
                placeholder="请输入宝塔Hook密匙"
              />
            </el-form-item>

            <el-form-item label="统计代码:">
              <el-input
                v-model="form.BaiduCode"
                :rows="3"
                clearable
                placeholder="请输入百度统计代码"
                type="textarea"
              />
            </el-form-item>

            <el-form-item label="版权信息:">
              <el-input
                v-model="form.Copyright"
                :rows="3"
                clearable
                placeholder="请输入站点版权信息"
                type="textarea"
              />
            </el-form-item>

            <el-form-item label="状态:">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="0"
              />
              <el-popover
                content="选择关闭后网站不会再展示任何客服信息。"
                placement="top-start"
                trigger="hover"
                width="240"
              >
                <i
                  slot="reference"
                  class="el-icon-_question"
                  style="vertical-align: middle; margin-left: 8px"
                ></i>
              </el-popover>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="updateVisible(false)">取消 </el-button>
        <el-button :loading="loading" type="primary" @click="save"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="宝塔HOOK安装使用教程"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      top="50px"
      :visible.sync="helpVideoVisible"
    >
      <el-tabs v-model="active">
        <el-tab-pane label="安装代码" name="code"></el-tab-pane>
        <el-tab-pane label="视频教程" name="player"></el-tab-pane>
      </el-tabs>
      <div style="margin-top: 15px">
        <div v-if="active === 'code'">
          <el-input
            v-model="installCode"
            ref="installCode"
            :readonly="true"
            :rows="24"
            type="textarea"
          />
        </div>
        <div v-if="active === 'player'">
          <xgplayer :config="config" @player="onPlayer" />
        </div>
      </div>
      <div slot="footer">
        <el-button @click="copyCode">复制代码</el-button>
        <el-button type="primary" @click="helpVideoVisible = false"
          >明白</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      width="820px"
      title="查看绑定域名"
      :visible.sync="helpdialogVisible"
    >
      <span
        >请打开宝塔面板，点击网站管理, 找到根目录,
        得到根目录后面的域名即可。</span
      >
      <img
        src="~@/assets/image/domain-name.png"
        style="margin-top: 10px"
        alt=""
      />
    </el-dialog>
  </div>
</template>

<script>
import setting from "@/config/setting";
import Xgplayer from "xgplayer-vue";

export default {
  name: "UserEdit",
  components: { Xgplayer },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },
  data() {
    return {
      active: "code",
      player: null,
      ready: false,
      config: {
        id: "demoPlayer1",
        lang: "zh-cn",
        // 宽度100%
        fluid: true,
        // 视频地址
        url: "https://travel.jiafen520.com/qr/c99d44982f0eff665afc9d673797245115215d0f.mp4",
        // 封面
        poster:
          "http://travel.jiafen520.com/qr/7473e9e9a54ab839aa18ce0f7437850137bf0726.jpg",
        // 开启倍速播放
        playbackRate: [0.5, 1, 1.5, 2],
        // 开启画中画
        pip: true,
      },
      helpdialogVisible: false,
      installCode:
        "\t#!/bin/bash\n" +
        "\tfunction setTemplate() {\n" +
        '\t	datetime=$(date +"%Y-%m-%d %T")\n' +
        '\t	echo "[$datetime] 站点安装目录: "${1}\n' +
        "\t	if [[ ${1} -ne /www/wwwroot/* ]];then\n" +
        '\t		echo "[$datetime] 检测到站点安装目录异常."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        '\t	if [ ! -d "${1}" ];then\n' +
        '\t		echo "[$datetime] 检测到站点安装目录不存在."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	cd ${1}\n" +
        '\t	downloadPath=${1}"/source.zip"\n' +
        '\t	if [ -f "$downloadPath" ];then\n' +
        "\t		rm -rf $downloadPath\n" +
        "\t	fi\n" +
        '\t	echo "[$datetime] 文件保存名称: "$downloadPath\n' +
        '\t	echo "[$datetime] 开始下载文件: "${2}\n' +
        "\t	wget -O $downloadPath ${2} --no-check-certificate > /dev/null\n" +
        "\t	if [ $? -ne 0 ]; then\n" +
        '\t		echo "[$datetime] Wget命令执行异常, 站点源码下载失败."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        '\t	if [ ! -f "$downloadPath" ];then\n' +
        '\t		echo "[$datetime] 文件下载失败, 请确保下载链接是否正确."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	unzip -t $downloadPath > /dev/null\n" +
        "\t	if [ $? -ne 0 ]; then\n" +
        '\t		echo "[$datetime] 站点操作失败, 服务器不支持unzip."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	unzip -o ${downloadPath} > /dev/null\n" +
        "\t	if [ $? -ne 0 ]; then\n" +
        '\t		echo "[$datetime] 站点操作失败, Zip解压失败."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        '\t	if [ -f "$downloadPath" ];then\n' +
        "\t		rm -rf $downloadPath\n" +
        "\t	fi\n" +
        '\t	echo "[$datetime] 文件下载成功, 开始执行操作站点."\n' +
        '\t	echo "[$datetime] 站点操作成功."\n' +
        '\t	templateLog=${1}"/mm-template.log"\n' +
        '\t	if [ -f "$templateLog" ];then\n' +
        "\t		rm -rf $templateLog\n" +
        "\t	fi\n" +
        "\t	cp /www/server/panel/plugin/webhook/script/*.log $templateLog > /dev/null\n" +
        "\t	return\n" +
        "\t}\n" +
        "\tfunction setNginx() {\n" +
        '\t	datetime=$(date +"%Y-%m-%d %T")\n' +
        '\t	rootPath="root \\/www\\/wwwroot\\/$1;"\n' +
        "\t	nginxFile=/www/server/panel/vhost/nginx/$1.conf\n" +
        '\t	echo "[$datetime] Nginx配置目录: "${nginxFile}\n' +
        '\t	if [ ! -f "$nginxFile" ];then\n' +
        '\t		echo "[$datetime] 检测到绑定域名不存在."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	downloadFile=/www/server/panel/vhost/nginx/$1.log\n" +
        '\t	if [ -f "$downloadFile" ];then\n' +
        "\t		rm -rf $downloadFile\n" +
        "\t	fi\n" +
        '\t	echo "[$datetime] Nginx文件保存名称: "$downloadFile\n' +
        '\t	echo "[$datetime] 开始下载Nginx文件: "${2}\n' +
        "\t	wget -O $downloadFile ${2} --no-check-certificate > /dev/null\n" +
        "\t	if [ $? -ne 0 ]; then\n" +
        '\t		echo "[$datetime] Nginx配置文件下载失败, Wget命令执行异常."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        '\t	if [ ! -f "$downloadFile" ];then\n' +
        '\t		echo "[$datetime] Nginx配置文件下载失败, 请确保下载链接是否正确."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        '\t	if [ `grep -c "access_page begin tag" ${downloadFile}` -eq 0 ];then\n' +
        '\t		echo "[$datetime] Nginx配置文件异常, 未检测到Nginx特征码."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	rootContent=`cat $downloadFile`\n" +
        '\t	if [ -f "$downloadFile" ];then\n' +
        "\t		rm -rf $downloadFile\n" +
        "\t	fi\n" +
        "\t	if [ `grep -c \"access_page begin tag\" ${nginxFile}` -ne '0' ];then\n" +
        '\t		sed -i "/#access_page begin tag/,/#access_page end tag/c${rootContent}" ${nginxFile} > /dev/null\n' +
        "\t	else\n" +
        '\t		sed -i "s/${rootPath}/${rootContent}/g" ${nginxFile} > /dev/null\n' +
        "\t	fi\n" +
        "\t	if [ $? -ne 0 ];then\n" +
        '\t		echo "[$datetime] Nginx部署失败, 命令执行异常."\n' +
        "\t		return\n" +
        "\t	fi\n" +
        "\t	nginx -s reload > /dev/null\n" +
        '\t	echo "[$datetime] Nginx部署成功."\n' +
        "\t	return\n" +
        "\t}\n" +
        "\tparam=${1}\n" +
        "\tparamArray=(${param//;/ })\n" +
        '\tdatetime=$(date +"%Y-%m-%d %T")\n' +
        "\tcat /dev/null > /www/server/panel/plugin/webhook/script/*.log > /dev/null\n" +
        '\techo "[$datetime] 检测系统环境"\n' +
        "\tcase ${paramArray[0]} in\n" +
        '\t	"setTemplate")\n' +
        "\t		setTemplate ${paramArray[1]} ${paramArray[2]}\n" +
        "\t		;;\n" +
        '\t	"setNginx")\n' +
        "\t		setNginx ${paramArray[1]} ${paramArray[2]}\n" +
        "\t		;;\n" +
        "\t	*)\n" +
        "\t	 Default condition to be executed\n" +
        "\t	 ;;\n" +
        "\tesac\n",
      // 表单数据
      showbPage: false,
      // 视频教学
      helpVideoVisible: false,
      // 展示模式
      modelList: [
        { value: 0, label: "随市场展示" },
        { value: 1, label: "均衡展示" },
        { value: 2, label: "随机展示" },
        { value: 3, label: "权重展示" },
        { value: 4, label: "轮番展示" },
      ],
      form: Object.assign(
        {
          status: 1,
          bazaar: "",
          SiteModel: "",
        },
        this.data
      ),
      // 表单验证规则
      rules: {
        SiteName: [
          { required: true, message: "站点名称不能为空", trigger: "blur" },
        ],
        DomainUrl: [
          {
            required: true,
            type: "string",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入落地页"));
              }
              this.$http
                .get("/website/query?url=" + value)
                .then((res) => {
                  if (res.data.code !== 0 || !res.data.data.length) {
                    return callback();
                  }
                  if (
                    this.isUpdate &&
                    res.data.data[0].url === this.data.DomainUrl
                  ) {
                    return callback();
                  }
                  callback(new Error("落地页URL已存在"));
                })
                .catch(() => {
                  callback();
                });
            },
          },
        ],
        bazaar: [
          { required: true, message: "请选择推广市场", trigger: "blur" },
        ],
        url: [
          {
            required: true,
            message: "请输入网站能访问的地址.",
            trigger: "blur",
          },
        ],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 市场列表
      bazaarList: [],
      // 上传标题
      uploadText: "上传",
      // 上传状态
      uploadLoading: false,
      //上传头部
      headersUpload: {
        Authorization: setting.takeToken(),
      },
    };
  },
  watch: {
    data() {
      if (Object.keys(this.data).length > 0) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
        this.showbPage = this.data.abswitch === 1;
      } else {
        for (let i in this.form) {
          this.form[i] = null;
        }
        this.form.status = 1;
        this.isUpdate = false;
      }
    },
  },
  mounted() {
    this.queryRoles(); // 搜索列表
  },
  methods: {
    select(element) {
      let selectedText;
      if (element.nodeName === "SELECT") {
        element.focus();
        selectedText = element.value;
      } else if (
        element.nodeName === "INPUT" ||
        element.nodeName === "TEXTAREA"
      ) {
        let isReadOnly = element.hasAttribute("readonly");
        if (!isReadOnly) {
          element.setAttribute("readonly", "");
        }
        element.select();
        element.setSelectionRange(0, element.value.length);
        if (!isReadOnly) {
          element.removeAttribute("readonly");
        }
        selectedText = element.value;
      } else {
        if (element.hasAttribute("contenteditable")) {
          element.focus();
        }
        let selection = window.getSelection();
        let range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
        selectedText = selection.toString();
      }
      return selectedText;
    },
    copy(element) {
      try {
        this.select(element);
        return document.execCommand("copy");
      } catch (err) {
        return false;
      }
    },
    copyCode() {
      let result = this.copy(this.$refs.installCode.$el);
      if (result) {
        this.loading = false;
        return this.$message({
          type: "success",
          message: "已成功复制，可直接去粘贴!",
        });
      }
      this.loading = false;
    },
    onPlayer(e) {
      this.player = e;
      this.player.on("play", () => {
        this.ready = true;
      });
    },

    helpVideo() {
      this.active = "code";
      this.helpVideoVisible = true;
    },

    helpImage() {
      this.helpdialogVisible = true;
    },

    bazaarChange(obj) {
      if (!this.isUpdate) {
        for (let i = 0; i < this.bazaarList.length; i++) {
          if (this.bazaarList[i].id === obj) {
            this.form.SiteModel = this.bazaarList[i].model;
            break;
          }
        }
      }
    },
    abpage(value) {
      this.showbPage = value === 1;
    },
    baseURLUpload() {
      return process.env.VUE_APP_API_BASE_URL + "/website/upload";
    },
    beforeUpload(file) {
      const isZip = file.type === "application/x-zip-compressed";
      if (!isZip) {
        this.$message.error("上传文件只能是 Zip 格式!");
        return false;
      }
      const isLt15M = file.size / 1024 / 1024 < 15;
      if (!isLt15M) {
        this.$message.error("上传文件大小不能超过 15MB!");
        return false;
      }
      const valid = isZip && isLt15M;
      if (valid) {
        this.uploadLoading = true;
      }
      return valid;
    },
    errorUpload() {
      this.uploadText = "上传";
      this.uploadLoading = false;
      this.$message.error("上传失败!");
    },
    successUpload(obj) {
      this.uploadText = "上传";
      this.uploadLoading = false;
      if (obj.code === 0) {
        this.form.SiteSource = obj.url;
        this.$message({
          message: "上传成功!",
          type: "success",
        });
      } else {
        this.$message.error(obj.msg);
      }
    },
    /*上传进度*/
    progressUpload(event) {
      if (event.isTrusted) {
        this.uploadText = parseInt(event.percent) + "%";
      }
    },
    /* 确定编辑 */
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$http
            .post(
              "/website/" + [this.isUpdate ? "update" : "create"],
              this.form
            )
            .then((res) => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message({ type: "success", message: res.data.msg });
                if (!this.isUpdate) {
                  for (let i in this.form) {
                    this.form[i] = null;
                  }
                  this.form.status = 1;
                }
                this.updateVisible(false);
                this.$emit("done", this.isUpdate);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
    },
    /* 搜索列表 */
    queryRoles() {
      this.$http
        .get("/website/getBazaar")
        .then((res) => {
          if (res.data.code === 0) {
            this.$emit("childFn", res.data.data);
            this.bazaarList = res.data.data;
            if (this.bazaarList.length > 1) {
              this.bazaarList.sort(function (a, b) {
                return b.status - a.status;
              });
            }
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
  },
};
</script>

<style scoped></style>
